<template>
  <div class="lodgingPane">
    <div>
      <TaiTitle title="入住人基本信息">
        <el-button class="mt5" link type="warning" @click="handleBaseInfoEdit">编辑</el-button>
        <template #append>
          <div v-if="!mobile">
            <el-button plain @click="handleAddContract">添加合同</el-button>
            <el-button plain @click="checkOutMessageBox">退 房</el-button>
            <el-button plain @click="handleContinue">续 租</el-button>
          </div>
          <el-dropdown trigger="click" placement="bottom-start" v-else @command="baseInfoCommand">
            <el-icon class="ml20" style="cursor: pointer;"><MoreFilled /></el-icon>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="add">添加合同</el-dropdown-item>
                <el-dropdown-item command="checkOut">退 房</el-dropdown-item>
                <el-dropdown-item command="continue">续 租</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </TaiTitle>
      <div class="primary-section mt20">
        <el-form label-width="80px">
          <el-row>
            <el-col :span="12" :xs="24">
              <el-form-item label="姓名">{{ mainRenter.name }}</el-form-item>
            </el-col>
            <el-col :span="12" :xs="24">
              <el-form-item label="证件号">{{ mainRenter.idCardNumber }}</el-form-item>
            </el-col>
            <el-col :span="12" :xs="24">
              <el-form-item label="联系方式">{{ mainRenter.contacts }}</el-form-item>
            </el-col>
            <el-col :span="12" :xs="24">
              <el-form-item label="入住周期">{{ checkInInfo.checkInStart }}至{{ checkInInfo.checkInEnd }}</el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>
    <div class="mt20">
      <TaiTitle title="同住人信息" class="mb20">
        <el-button plain @click="handleCohabitants('add')">添加同住人</el-button>
      </TaiTitle>
      <div class="primary-section mb5 pv-12" style="color: var(--el-text-color-secondary);" v-if="cohabitantsList.length === 0">暂无同住人信息</div>
      <div class="primary-section mb5" v-for="item in cohabitantsList" :key="item.id">
        <el-form label-width="80px">
          <el-row :align="mobile ? 'top' : 'middle'">
            <el-col :span="18" :xs="16">
              <el-row>
                <el-col :span="10" :xs="24">
                  <el-form-item label="姓名">{{ item.name }}</el-form-item>
                </el-col>
                <el-col :span="14" :xs="24">
                  <el-form-item label="联系方式">{{ item.contacts }}</el-form-item>
                </el-col>
              </el-row>
            </el-col>
            <div style="margin-left: auto;" :style="{'margin-top': mobile ? '6px' : '0'}">
              <el-button link type="primary" @click="handleCohabitants('edit', item)">编辑</el-button>
              <el-button link type="danger" @click="handleCohabitantsRemove(item)">删除</el-button>
            </div>
          </el-row>
        </el-form>
      </div>
    </div>
    <div class="mt20">
      <TaiTitle title="房租信息" class="mb20">
        <el-button class="mt5" link type="warning" @click="handleRentRange">编辑</el-button>
      </TaiTitle>
      <div class="primary-section">
        <el-form label-width="80px">
          <el-row align="top">
            <el-col :span="24">
              <el-row>
                <el-col :span="8">
                  <el-form-item label="月租金">{{ rentRangeInfo.rent ? rentRangeInfo.rent : '--' }}</el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="押金">{{ rentRangeInfo.deposit ? rentRangeInfo.deposit : '--' }}</el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="付款方式">{{ rentRangeInfo.rentType ? rentRangeInfo.rentType : '--' }}</el-form-item>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>
    <!-- <div class="mt20">
      <TaiTitle title="合同信息" class="mb20"></TaiTitle>
      <div class="primary-section mb5 pv-12" style="color: var(--el-text-color-secondary);" v-if="contractInfo">暂无合同信息</div>
      <div class="primary-section">
        <el-form label-width="80px">
          <el-row align="top">
            <el-col :span="22" :xs="21">
              <el-row>
                <el-col :span="15" v-if="!mobile">
                  <el-form-item label="合同周期">{{ contractInfo.checkInStart }} 至 {{ contractInfo.checkInEnd }}</el-form-item>
                </el-col>
                <el-col :span="9" :xs="12">
                  <el-form-item label="月租金">{{ contractInfo.rent }}</el-form-item>
                </el-col>
                <el-col :span="15" :xs="12">
                  <el-form-item label="支付方式">{{ contractInfo.type }}</el-form-item>
                </el-col>
                <el-col :span="24" v-if="mobile">
                  <el-form-item label="合同周期">{{ contractInfo.checkInStart }} 至 {{ contractInfo.checkInEnd }}</el-form-item>
                </el-col>
              </el-row>
            </el-col>
            <div style="margin-left: auto;margin-top: 6px;">
              <el-button link type="primary">查看</el-button>
            </div>
          </el-row>
        </el-form>
      </div>
    </div> -->
    <div class="mt20">
      <TaiTitle title="备注" class="mb20">
        <el-button class="mt5" link type="warning" @click="handleRemark">编辑</el-button>
      </TaiTitle>
      <div class="primary-section pv-12">
        {{ checkInInfo.remark ? checkInInfo.remark : '暂无备注'  }}
      </div>
    </div>
    <!-- <div class="mt20">
      <TaiTitle title="视频图片" class="mb20">
        <el-button class="mt5" link type="warning">编辑</el-button>
      </TaiTitle>
      <div class="primary-section pv-12"  style="color: var(--el-text-color-secondary);">
        暂无视频图片
      </div>
    </div> -->
    <!-- 入住人基本信息编辑弹窗 -->
    <el-dialog title="入住人基本信息" v-model="baseInfoVisible" width="550px" :fullscreen="mobile">
      <el-form :model="baseInfoForm" ref="baseInfoFormRef" :rules="baseInfoRules" label-width="80px">
        <el-row>
          <el-col :span="22">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="baseInfoForm.name" placeholder="请输入姓名"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item label="联系方式" prop="contacts">
              <el-input v-model="baseInfoForm.contacts" placeholder="请输入联系方式"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item label="证件号" prop="idCardNumber">
              <el-input v-model="baseInfoForm.idCardNumber" placeholder="请输入证件号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-icon class="mt10 ml10"><Wallet /></el-icon>
          </el-col>
          <el-col :span="20">
            <el-form-item label="入住照片" prop="picUrl">
              <el-upload
                  :action="uploadUrl"
                  :headers="headers"
                  class="avatar-uploader"
                  :before-upload="beforeAvatarUpload"
                  :on-success="handleAvatarSuccess"
                  :show-file-list="false">
                <img v-if="imageUrl" :src="imageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="入住周期" required>
              <el-row>
                <el-col :span="11">
                  <el-form-item label-width="0" prop="startDate">
                    <el-date-picker
                      v-model="baseInfoForm.startDate"
                      :editable="false"
                      value-format="YYYY-MM-DD"
                      type="date"
                      placeholder="请选择开始日期"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="2">
                  <div style="text-align: center;">-</div>
                </el-col>
                <el-col :span="11">
                  <el-form-item label-width="0" prop="endDate">
                    <el-date-picker
                      v-model="baseInfoForm.endDate"
                      value-format="YYYY-MM-DD"
                      type="date"
                      :editable="false"
                      placeholder="请选择结束日期"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleBaseInfoClose">取消</el-button>
          <el-button type="primary" @click="handleBaseInfoOk">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 添加合同弹窗 -->
    <el-dialog title="添加合同" v-model="contractVisible" width="750px" :fullscreen="mobile">
      <el-form :model="contractForm" :rules="contractRules" ref="contractFormRef" :label-width="mobile ? '80px' : '120px'">
        <el-row>
          <el-col :span="20">
            <el-form-item label="选择模板" prop="contractTemplateId" required>
              <el-select v-model="contractForm.contractTemplateId" style="width: 80%;">
                <el-option label="房屋租赁合同" value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item label="入住周期" required>
              <el-row>
                <el-col :span="11">
                  <el-form-item label-width="0" prop="startDate">
                    <el-date-picker
                      v-model="contractForm.startDate"
                      :editable="false"
                      type="date"
                      placeholder="请选择开始日期"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="2">
                  <div style="text-align: center;">-</div>
                </el-col>
                <el-col :span="11">
                  <el-form-item label-width="0" prop="endDate">
                    <el-date-picker
                      v-model="contractForm.endDate"
                      type="date"
                      :editable="false"
                      placeholder="请选择结束日期"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>
          <el-col :span="11" :xs="22">
            <el-form-item label="租金" required>
              <el-row>
                <el-col :span="10">
                  <el-form-item prop="rentCollectType" label-width="0">
                    <el-select v-model="contractForm.rentCollectType">
                      <el-option label="月租金" value="1"></el-option>
                      <el-option label="日租金" value="2"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="14">
                  <el-form-item prop="rent" label-width="0">
                    <el-input v-model="contractForm.rent" placeholder="请输入租金"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>
          <el-col :span="11" :xs="22">
            <el-form-item label="押金" prop="deposit">
              <el-input v-model="contractForm.deposit" placeholder="请输入押金"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11" :xs="22">
            <el-form-item label="居住人数" prop="people">
              <el-input v-model.number="contractForm.people" placeholder="请输入居住人数"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11" :xs="22">
            <el-form-item label="面积" prop="area">
              <el-input-number
                v-model="contractForm.area"
                :controls="false"
                placeholder="请输入面积"
                style="text-align: left;width: 100%;"
              ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="11" :xs="22">
            <el-form-item label="支付时间" prop="rentCycle" required>
              <el-select v-model="contractForm.rentCycle" placeholder="请选择支付时间">
                <el-option label="每1月" value="1"></el-option>
                <el-option label="每2月" value="2"></el-option>
                <el-option label="每3月" value="3"></el-option>
                <el-option label="每4月" value="4"></el-option>
                <el-option label="每半年" value="5"></el-option>
                <el-option label="每一年" value="6"></el-option>
                <el-option label="一次性" value="7"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11" :xs="22">
            <el-form-item label="用途" prop="useType" required>
              <el-select v-model="contractForm.useType" placeholder="请选择用途">
                <el-option label="居住" value="1"></el-option>
                <el-option label="商业" value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item label="房间物品" prop="configDesc">
              <el-input type="textarea" v-model="contractForm.configDesc" :rows="3"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item label="其他约定" prop="otherAgree">
              <el-input type="textarea" v-model="contractForm.otherAgree" :rows="3"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button>合同预览</el-button>
          <el-button type="primary" @click="handleContractOk">
            完成
          </el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 续租弹窗 -->
    <el-dialog title="续租至" v-model="continueVisible" width="380px" @close="handleContinueCancel">
      <el-form :model="continueForm" label-width="80px" ref="continueFormRef">
        <el-form-item prop="checkInEnd" label="选择时间" :rules="[{required: true, message: '请选择续租结束日期', trigger: 'blur'}]">
          <el-date-picker
            v-model="continueForm.checkInEnd"
            type="date"
            :editable="false"
            value-format="YYYY-MM-DD"
            placeholder="请选择续租结束日期"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleContinueCancel">取消</el-button>
          <el-button type="primary" @click="handleContinueOk">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 添加同住人弹窗 -->
    <CohabitantsDl
      :visible="cohabitants.visible"
      :type="cohabitants.type"
      :form="cohabitants.form"
      @cancel="handleCohabitantsClose"
      @ok="handleCohabitantsOk"
    />
    <!-- 编辑备注信息弹窗 -->
    <el-dialog title="编辑" v-model="remarkVisible" width="520px" :fullscreen="mobile">
      <el-form :model="remarkForm" ref="remarkFormRef" label-width="0">
        <el-form-item prop="remark">
          <el-input type="textarea" v-model="remarkForm.remark" :rows="4" maxlength="150" placeholder="请填写备注信息" show-word-limit></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleRemarkClose">取消</el-button>
          <el-button type="primary" @click="handleRemarkOk">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
    <RentRangeDl
      :visible="rentRange.visible"
      :type="rentRange.type"
      :form="rentRange.form"
      @cancel="handleRentRangeClose"
      @ok="handleRentRangeOk"
    />
  </div>
</template>
<script setup name="LodgingPane">
import { ElMessage, ElMessageBox } from 'element-plus'
import useAppStore from '@/store/modules/app'
import CohabitantsDl from '../cohabitantsDl.vue'
import checkInApi from '@/api/room/checkin'
import renterApi from '@/api/room/renter'
import RentRangeDl from '@/views/room/checkin/rentRangeDl.vue'
import useUserStore from '@/store/modules/user'
import { inject } from 'vue'
import {getToken} from "@/utils/auth.js";

const { proxy } = getCurrentInstance()

const props = defineProps({
  checkInId: [String, Number]
})

const uploadUrl = ref(import.meta.env.VITE_APP_BASE_API + "/file/upload"); // 上传的图片服务器地址
const headers = ref({ authorization: getToken() })
const imageUrl = ref('')

const baseInfoVisible = ref(false)
const contractVisible = ref(false)
const continueVisible = ref(false)
const cohabitants = ref({
  visible: false,
  type: '',
  form: {}
})
const remarkVisible = ref(false)
const cohabitantsList = ref([])
const rentRangeInfo = ref({})
// const checkInInfo = ref({})
const { checkInInfo, updateCheckInInfo } = inject('checkInInfo')
const mainRenter = ref([])
const mobile = computed(() => useAppStore().device === 'mobile')
watch(() => checkInInfo.value, value => {
  if (value && Object.keys(value).length > 0) {
    rentRangeInfo.value = {
      ...value.rentObject,
      checkInStart: value.checkInStart,
      checkInEnd: value.checkInEnd
    }
    cohabitantsList.value = value.renterList.filter(item => item.mainFlag === '0')
    mainRenter.value = value.renterList.find(item => item.mainFlag === '1') || {}
  }
}, { immediate: true })
const data = reactive({
  baseInfoForm: {
    renterId: undefined,
    name: undefined,
    contacts: undefined,
    idCardNumber: undefined,
    startDate: '',
    endDate: ''
  },
  contractForm: {
    contractTemplateId: '1',
    startDate: '',
    endDate: '',
    rentCollectType: '1',
    rent: undefined,
    deposit: undefined,
    people: '1',
    area: undefined,
    rentCycle: '1',
    useType: '1'
  },
  continueForm: {
    checkInEnd: ''
  },
  cohabitantsForm: {
    renterName: undefined,
    contacts: undefined,
    idNumber: undefined,
  },
  rentRange: {
    visible: false,
    type: 'add',
    form: {}
  },
  remarkForm: {
    remark: undefined
  },
  baseInfoRules: {
    name: [{ required: true, message: "请输入名字", trigger: "blur" }],
    contacts: [{ required: true, pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }],
    startDate: [{ required: true, type: 'date', message: "请选择开始日期", trigger: "blur" }],
    endDate: [{ required: true, type: 'date', message: "请选择结束日期", trigger: ["blur"] }],
  },
  contractRules: {
    rent: [
      { required: true, message: "请输入租金", trigger: "blur" },
      { pattern: /^(0|([1-9][0-9]*))?(.\d{1,2})?$/, message: "请输入正确的租金", trigger: ["blur", "change"] }
    ],
    area: [
      { required: true, message: "请输入面积", trigger: "blur" },
      { pattern: /^(0|([1-9][0-9]*))?(.\d{1,2})?$/, message: "请输入正确的面积", trigger: ["blur", "change"] }
    ],
    deposit: [
      { required: true, message: "请输入押金", trigger: "blur" },
      { pattern: /^(0|([1-9][0-9]*))?(.\d{1,2})?$/, message: "请输入正确的押金", trigger: ["blur", "change"] }
    ],
    people: [
      { required: true, message: "请输入居住人数", trigger: "blur" },
      { pattern: /^([1-9][0-9]*)$/, message: "请输入正确的居住人数", trigger: ["blur", "change"] }
    ],
    startDate: [{ required: true, message: "请选择开始居住日期", trigger: "blur" }],
    endDate: [{ required: true, message: "请选择结束居住日期", trigger: "blur" }],
  },
  cohabitantsRules: {
    renterName: [{ required: true, message: "请输入名字", trigger: "blur" }],
    contacts: [{ required: true, pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }],
  },
})
const { baseInfoForm, baseInfoRules, contractForm, contractRules, continueForm, cohabitantsForm, cohabitantsRules, remarkForm, rentRange } = toRefs(data)

// 入住人基本信息编辑
function resetBaseInfoForm() {
  baseInfoForm.value = {
    renterId: undefined,
    name: undefined,
    contacts: undefined,
    idCardNumber: undefined,
    startDate: '',
    endDate: ''
  }
  proxy.resetForm('baseInfoFormRef')
}
function handleBaseInfoEdit() {
  // resetBaseInfoForm()
  baseInfoForm.value = { ...mainRenter.value, startDate: rentRangeInfo.value.checkInStart, endDate: rentRangeInfo.value.checkInEnd }
  imageUrl.value = mainRenter.value.picUrl
  baseInfoVisible.value = true
}
function handleBaseInfoClose() {
  baseInfoVisible.value = false
}
function handleBaseInfoOk() {
  proxy.$refs['baseInfoFormRef'].validate(valid => {
    if (valid) {
      // 如果没有renterId，报错
      if (!baseInfoForm.value.renterId) {
        proxy.$modal.msgError('请先添加入住人')
        return
      }
      // 更新入住人人脸
      if (imageUrl.value && imageUrl.value !== '') {
        baseInfoForm.value.picUrl = imageUrl.value
        // 调用人身核验接口
        renterApi.verify(baseInfoForm.value.renterId, baseInfoForm.value.picUrl, baseInfoForm.value.name, baseInfoForm.value.idCardNumber)
            .then(res => {
              if (res.code === 200) {
                // 核验成功后调用保存接口
                saveBaseInfo()
              }
            })
      } else {
        saveBaseInfo()
      }
    }
  })
}

/* 保存基本信息 */
function saveBaseInfo() {
  let checkInInfo = {
    checkInId: props.checkInId,
    checkInStart: baseInfoForm.value.startDate,
    checkInEnd: baseInfoForm.value.endDate
  }

  // 更新入住人人脸
  if (imageUrl.value && imageUrl.value !== '') {
    baseInfoForm.value.picUrl = imageUrl.value
  }

  Promise.all([
    checkInApi.update(checkInInfo), 
    renterApi.edit(baseInfoForm.value)
  ]).then(res => {
    baseInfoVisible.value = false
    proxy.$modal.msgSuccess('更新成功')
    updateCheckInInfo()
  })
}

// 基础信息 操作按钮下拉选择
function baseInfoCommand(value) {
  switch (value) {
    // 添加合同
    case 'add':
      handleAddContract()
      break;
    // 退房
    case 'checkOut':
      checkOutMessageBox()
      break
    // 续租
    case 'continue':
      handleContinue()
      break
    default:
      break;
  }
}

// 添加合同
function resetContractForm() {
  contractForm.value = {
    contractTemplateId: '1',
    startDate: '',
    endDate: '',
    rentCollectType: '1',
    rent: undefined,
    deposit: undefined,
    people: '1',
    area: undefined,
    rentCycle: '1',
    useType: '1'
  }
  proxy.resetForm('contractFormRef')
}
function handleAddContract() {
  resetContractForm()
  contractVisible.value = true
}
function handleContractOk() {
  proxy.$refs['contractFormRef'].validate(valid => {
    if (valid) {
      contractVisible.value = false
      proxy.$modal.msgSuccess("合同添加成功");
    }
  })
}

// 退房操作提示
function checkOutMessageBox() {
  ElMessageBox.confirm(
    '退房后，房间将变成空置状态',
    '',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      customStyle: 'width: 320px;'
    }
  )
    .then(() => {
      checkInApi.out(props.checkInId).then(() => {
        ElMessage({
          type: 'success',
          message: '退房成功',
        })
        updateCheckInInfo()
      })
      
    })
    .catch(() => console.log('delete...'))
}

/* 续租 */
function resetContinueForm() {
  continueForm.value = {
    checkInEnd: ''
  }
  proxy.resetForm('continueFormRef')
}
function handleContinue() {
  resetContinueForm()
  continueForm.value.checkInEnd = checkInInfo.value.checkInEnd
  continueVisible.value = true
}
function handleContinueOk() {
  proxy.$refs['continueFormRef'].validate(valid => {
    if (valid) {
      if (continueForm.value.checkInEnd === checkInInfo.value.checkInEnd) {
        continueVisible.value = false
      } else {
        checkInApi.update({ checkInId: props.checkInId, checkInEnd: continueForm.value.checkInEnd }).then(() => {
          continueVisible.value = false
          proxy.$modal.msgSuccess('续租成功')
          updateCheckInInfo()
        })
      }
    }
  })
}
function handleContinueCancel() {
  continueVisible.value = false
}

/* 同住人 */
function handleCohabitants(type, row) {
  console.log(cohabitants);
  cohabitants.value.type = type
  if (type === 'edit') {
    cohabitants.value.form = { ...row }
  }
  cohabitants.value.visible = true
}
function handleCohabitantsRemove(item) {
  ElMessageBox.confirm(
    '确定删除同住人？',
    '',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      customStyle: 'width: 320px;'
    }
  )
    .then(() => {
      renterApi.remove(item.renterId).then(() => {
        updateCheckInInfo()
        ElMessage({
          type: 'success',
          message: `删除成功${id}`,
        })
      })
    })
    .catch(() => console.log('delete...'))
}
function handleCohabitantsClose() {
  cohabitants.value.visible = false
}
function handleCohabitantsOk(type, params) {
  if (type === 'edit') {
    console.log(params)
    renterApi.edit(params).then(res => {
      proxy.$modal.msgSuccess('编辑成功')
      cohabitants.value.visible = false
      updateCheckInInfo()
    })
  } else if (type === 'add') {
    // 此处mainFlag默认为非主要入住人
    renterApi.add({
      ...params,
      checkInId: props.checkInId,
      apartmentId: useUserStore().apartment.apartmentId,
      mainFlag: '0'
    }).then(res => {
      proxy.$modal.msgSuccess('新增成功')
      cohabitants.value.visible = false
      updateCheckInInfo()
    })
  }
}

/* 添加房租信息 */
function handleRentRange() {
  rentRange.value.type = 'edit'
  rentRange.value.form = { ...rentRangeInfo.value }
  rentRange.value.visible = true
}
function handleRentRangeClose() {
  rentRange.value.visible = false
}
function handleRentRangeOk(value) {
  let params = {
    checkInId: props.checkInId,
    rentObject: { ...value }
  }
  checkInApi.update(params).then(res => {
    updateCheckInInfo()
    proxy.$modal.msgSuccess('编辑成功')
    rentRange.value.visible = false
  })
  
}

// 备注信息
function resetRemarkForm() {
  remarkForm.value = {
    remark: undefined
  }
}
function handleRemark() {
  resetRemarkForm()
  remarkForm.value.remark = checkInInfo.value.remark
  remarkVisible.value = true
}
function handleRemarkOk() {
  // 判断表单值是否发生改变
  if (remarkForm.value.remark === checkInInfo.value.remark) {
    remarkVisible.value = false
  } else {
    checkInApi.update({ checkInId: props.checkInId, remark: remarkForm.value.remark }).then(() => {
      updateCheckInInfo()
      remarkVisible.value = false
      proxy.$modal.msgSuccess('保存成功')
    })
  }
}
function handleRemarkClose() {
  remarkVisible.value = false
}

/* 压缩图片 */
function compressImage(file) {
  return new Promise((resolve) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = (e) => {
      const img = new Image()
      img.src = e.target.result
      img.onload = () => {
        // 创建canvas
        const canvas = document.createElement('canvas')
        const ctx = canvas.getContext('2d')

        // 计算压缩后的尺寸，保持宽高比
        let width = img.width
        let height = img.height
        const maxSize = 800 // 最大尺寸

        if (width > height && width > maxSize) {
          height = (height * maxSize) / width
          width = maxSize
        } else if (height > maxSize) {
          width = (width * maxSize) / height
          height = maxSize
        }

        // 设置canvas尺寸
        canvas.width = width
        canvas.height = height

        // 绘制图片
        ctx.drawImage(img, 0, 0, width, height)

        // 递归压缩，直到文件大小小于1MB
        function compress(quality = 0.6) {
          return new Promise(resolve => {
            canvas.toBlob(blob => {
              // 如果文件仍然大于1MB且质量大于0.1，继续压缩
              if (blob.size > 1024 * 1024 && quality > 0.1) {
                compress(quality - 0.1).then(resolve)
              } else {
                resolve(new File([blob], file.name, {
                  type: 'image/jpeg',
                  lastModified: Date.now()
                }))
              }
            }, 'image/jpeg', quality)
          })
        }

        // 开始压缩
        compress().then(resolve)
      }
    }
  })
}

/* 上传前处理 */
async function beforeAvatarUpload(file) {
  const isJPG = file.type === 'image/jpeg'
  const isLt1M = file.size / 1024 / 1024 < 1

  if (!isJPG) {
    proxy.$modal.msgError('上传头像图片只能是 JPG 格式!')
    return false
  }

  if (!isLt1M) {
    console.log("原始图片大小:", file.size / 1024 / 1024, "MB")
    // 如果图片大于1M，进行压缩
    const compressedFile = await compressImage(file)
    console.log("压缩后图片大小:", compressedFile.size / 1024 / 1024, "MB")
    
    // 替换原文件
    return compressedFile
  }

  return file
}

/* 上传成功回调 */
function handleAvatarSuccess(res, file) {
  console.log("上传文件大小:", file.size / 1024 / 1024, "MB")
  if (res.code === 200) {
    imageUrl.value = res.data.url
    proxy.$modal.msgSuccess('上传成功')
  } else {
    proxy.$modal.msgError(res.msg || '上传失败')
  }
}

/* 获取入住人 */
// function getCheckInInfo() {
//   checkInApi.getInfo(props.checkInId).then(res => {
//     checkInInfo.value = res.data
//     rentRangeInfo.value = {
//       ...res.data.rentObject,
//       checkInStart: res.data.checkInStart,
//       checkInEnd: res.data.checkInEnd
//     }
//     cohabitantsList.value = res.data.renterList.filter(item => item.mainFlag === '0')
//     mainRenter.value = res.data.renterList.find(item => item.mainFlag === '1') || {}
//   })
// }
// getCheckInInfo()
</script>
<style lang="scss" scoped>
.lodgingPane {
  :deep(.el-input-number) {
    .el-input__inner {
      text-align: left;
    }
  }
  .primary-section {
    .el-form-item--default {
      margin-bottom: 0;
    }
  }
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>